package com.example.musicplayer;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.example.musicplayer.activity.HomeActivity;
import com.example.musicplayer.broadcastreceiver.NotificationReceiver;
import com.example.musicplayer.entity.MusicList;
import com.example.musicplayer.provider.MusicListProvider;
import com.example.musicplayer.service.MusicService;
import com.example.musicplayer.util.MusicNotification;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private MusicService.MusicBinder mMusicService;
    private NotificationReceiver receiver;
    private ServiceConnection connection = new ServiceConnection() {
        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMusicService = (MusicService.MusicBinder) service;
            mMusicService.createNotification();
            mMusicService.updateNotification(MusicNotification.NOTIFICATION_ID);
            Log.i("====================", "创建通知");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    // 新建线程更新进度条
    private Handler mHandler = new Handler();
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            Log.i("==================", "正在加载资源");
            // 启动音乐服务
            Toast.makeText(getApplicationContext(), "正在加载音乐，请稍后……", Toast.LENGTH_SHORT).show();
            Intent musicIntent = new Intent(getApplicationContext(), MusicService.class);
            startService(musicIntent);
            bindService(musicIntent, connection, BIND_AUTO_CREATE);
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 动态获取权限
        getAuthorityIfNecessary();
        // 动态注册广播接收器
        receiver = new NotificationReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MusicNotification.ACTION_PREVIOUS);
        intentFilter.addAction(MusicNotification.ACTION_START_OR_PAUSE);
        intentFilter.addAction(MusicNotification.ACTION_NEXT);
        intentFilter.addAction(MusicNotification.ACTION_LIST);
        registerReceiver(receiver, intentFilter);
        // 新建我喜欢歌单
        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(MusicListProvider.CONTENT_URI,
                null,
                MusicList.MUSIC_LIST_NAME + "=" + "\"我喜欢\"",
                null,
                null);// 查找我喜欢歌单是否存在

        if (cursor == null) {
            Toast.makeText(this, "新建我喜欢歌单出错！", Toast.LENGTH_SHORT).show();
        }
        if (cursor != null && cursor.getCount() == 0) {     // 如果不存在，则新建”我喜欢“歌单
            Log.i("=====================", "没有我喜欢歌单");
            ContentValues values = new ContentValues();
            values.put(MusicList.MUSIC_LIST_NAME, "我喜欢");
            getContentResolver().insert(MusicListProvider.CONTENT_URI, values);
            Toast.makeText(this, "新建我喜欢歌单成功！", Toast.LENGTH_LONG).show();
            cursor.close();
        }

        // 权限已获得时，加载歌单
        if (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            mHandler.postDelayed(mRunnable, 1);
        }

        // 自动跳转到首页
        final Intent intent = new Intent(this, HomeActivity.class);
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                Log.i("=============", "准备跳转到主页面");
                startActivity(intent);
            }
        };
        timer.schedule(task, 100 * 30);
    }

    // 首次获得权限后执行
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 获取权限后启动服务
                mHandler.postDelayed(mRunnable, 1);
            } else {
                // Permission Denied
                Toast.makeText(this, "权限获取失败，音乐扫面失败", Toast.LENGTH_SHORT).show();
            }
        }
    }


    /**
     * 动态获取权限
     */
    private void getAuthorityIfNecessary() {
        if (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
        unregisterReceiver(receiver);
    }
}